﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using QuanLyThongTinCoSo.Entity;
using QuanLyThongTinCoSo.Model;

namespace QuanLyThongTinCoSo.Biz
{
    public class RoleBiz : BaseBiz
    {   
        public RoleBiz(Entities context)
        {
            DbContext = context;    
        }

        public override void Insert(BaseModel model)
        {
            DbContext.Roles.Add(model as Role);
            DbContext.SaveChanges();
        }

        public override void Update(BaseModel model)
        {
            DbContext.Entry(model).State = EntityState.Modified;
            DbContext.SaveChanges();
        }

        public override void Delete(BaseModel model)
        {
            DbContext.Roles.Attach(model as Role);
            DbContext.Roles.Remove(model as Role);
            DbContext.Entry(model).State = EntityState.Deleted;

            DbContext.SaveChanges();
        }

        public override void DeleteItems(List<BaseModel> models)
        {
            foreach (Role role in models)
            {
                DbContext.Roles.Attach(role);
                DbContext.Roles.Remove(role);
                DbContext.Entry(role).State = EntityState.Deleted;
            }

            DbContext.SaveChanges();
        }

        public override BaseModel GetItemById(int id)
        {
            return (from item in DbContext.Roles
                    where item.Id == id
                    select item).First();
        }

        public Role GetRoleByName(string roleName)
        {
            return DbContext.Roles.FirstOrDefault(r => r.RoleName == roleName);
        }
    }
}
